<template>
  <div :id="id" :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import echarts from "echarts";
import resize from "./mixins/resize";
import { getScatData } from "@/api/chart";
import { notify } from "@/utils/message";
import { transBookType } from "@/utils/book-type";

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: "chart",
    },
    id: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "200px",
    },
    height: {
      type: String,
      default: "200px",
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  mounted() {
    this.initChart();
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    initChart() {
      this.chart = echarts.init(document.getElementById(this.id));
      getScatData()
        .then((res) => {
          let data = transBookType(res.data.data);
          let data1 = this.getTopTenBooksByPrice(data); // 获取数据并处理好
          let data2 = [];
          data1.forEach((book) => {
            data2.push([book.price, book.total, book.name]);
          });
          console.log(data2);
          notify(1, "获取散点图数据");
          this.chart.setOption({
            title: {
              text: "图书类型数量与价格分布",
              subtext: "（全部图书）",
              left: "center",
            },
            tooltip: {
              trigger: "item",
              formatter: function (params) {
                return `${params.value[2]}<br>价格: ${params.value[0]} 元, 数量: ${params.value[1]} 本`;
              },
            },
            xAxis: {
              scale: true,
              name: "图书类别价格（元）",
            },
            yAxis: {
              scale: true,
              name: "图书类别总数（本）",
            },
            series: [
              {
                type: "effectScatter",
                symbolSize: 20,
              },
              {
                type: "scatter",
                data: data2,
              },
            ],
          });
        })
        .catch((err) => {
          console.log(err);
          notify(2, "获取散点图数据", err);
        });
    },
    getCategoryCounts(books) {
      const categoryCounts = books.reduce((acc, book) => {
        acc[book.bookTypeStr] = (acc[book.bookTypeStr] || 0) + 1;
        return acc;
      }, {});

      return categoryCounts;
    },

    getTopTenBooksByPrice(books) {
      const categoryCounts = this.getCategoryCounts(books);
      const sortedBooks = books.sort((a, b) => b.price - a.price);
      const topTenBooksWithPrice = sortedBooks
        .slice(0, books.length)
        .map((book) => ({
          name: book.bookTypeStr,
          price: book.price,
          total: categoryCounts[book.bookTypeStr],
        }));

      return topTenBooksWithPrice;
    },
  },
};
</script>
